﻿using AutoMapper;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.InvoiceTicket.order;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.InvoiceTicket.Order
{
    /// <summary>
    /// 添加订单
    /// </summary>
    public class OrderCreateCommandHandler : IRequestHandler<OrderCreateCommand, ApiResult<int>>
    {
        IMapper _mapper;
        IRepository<OrderModel> orderRep;
        public OrderCreateCommandHandler(IMapper mapper, IRepository<OrderModel> orderRep)
        {
            _mapper = mapper;
            this.orderRep = orderRep;
        }

        public async Task<ApiResult<int>> Handle(OrderCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            OrderModel order = _mapper.Map<OrderModel>(request);
            order.Id = YitIdHelper.NextId();
            order.CreateTime = DateTime.Now;
            var s1 = DateTime.Now.ToString("yyyyMMdd");
            var s2 = new Random().Next(100, 999);
            order.OrderCode = s1 + s2;
            var num = await orderRep.AddAsync(order);
            if (num > 0)
            {
                result = new ApiResult<int>().AddSuccess("生产订单", num);
            }
            else
            {
                result = new ApiResult<int>().AddFail("生产订单");
            }
            result.Data = num;
            return await Task.FromResult(result);
        }
    }
}
